﻿using System.Web;
using System.Text.RegularExpressions;

namespace MiserBlogHelper.Helper
{
    public class HttpHelper
    {
        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(result) || !IsIP(result))
                return "127.0.0.1";

            return result;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 与当前ip地址作比较 如果相同返回true
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool CompareTo(string ip)
        {
            ip = ip.Trim();
            if (ip == GetIP())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
